from rest_framework.response import Response
from django.db import transaction
from rest_framework.decorators import api_view
from functools import wraps
from customer import models
from django.conf import settings
import os
import time
import uuid
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from wfs.models import WorkflowApprovalRecord
from customer.sql import *

# 籤合
import tb_forms.models as tb
from method.method import case, WorkflowError, work_build
from itertools import chain
# from wfs.function.produce_pdf import delete_pdf,born_pdf
import wfs.function.produce_pdf as pf
import customer.functions as fun

os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'


# Create your views here.


def wrapp(func):
    """
        Response 跨域裝飾器
    """

    @wraps(func)
    def wrappde(*args, **kwargs):
        data = func(*args, **kwargs)
        re = Response(data)
        re['Access-Control-Allow-Origin'] = '*'
        re["Access-Control-Allow-Credentials"] = "true"
        re['Content-Type'] = 'application/json'
        return re

    return wrappde


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def CustomInfopk(request, pk):
    content = {"payload": [], "status": 1, "errmsg": ""}
    if request.method == 'GET':
        try:
            if pk:
                data = models.TbCustomInfo.objects.filter(id=pk).filter(delete_flag=1)
                for k in data.values():
                    k['create_time'] = k['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                    k['modify_time'] = k['modify_time'].strftime("%Y-%m-%d %H:%M:%S")
                    content['payload'] = k
                content['status'] = 1
                content['errmsg'] = ''
            else:
                content['payload'] = []
                content['status'] = 0
                content['errmsg'] = 'check your id.'
        except Exception as e:
            content['status'] = 0
            content['errmsg'] = str(e)
            content['payload'] = []

    if request.method == 'PUT':
        # 重名不能修改##
        try:
            c_name = request.POST.get('c_name')
            c_name_short = request.POST.get('c_name_short')
            c_num = request.POST.get('c_num')
            c_type = request.POST.get('c_type')
            c_site = request.POST.get('c_site')
            create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            if c_name or c_name_short or c_num or c_type or c_site:
                models.TbCustomInfo.objects.filter(id=int(pk)).update(
                    c_name=c_name, c_name_short=c_name_short, c_num=c_num, c_site=c_site,
                    c_type=c_type, modify_time=create_time, delete_flag=1)
                content['status'] = 1
                content['payload'] = '修改成功！'
                content['errmsg'] = ''
                return content
        except Exception as e:
            content['status'] = 0
            content['errmsg'] = str(e)
            content['payload'] = []

    if request.method == 'DELETE':
        try:
            if pk:
                models.TbCustomInfo.objects.filter(id=pk).update(delete_flag=0)
                content['status'] = 1
                content['payload'] = '刪除成功！'
                content['errmsg'] = ''
            else:
                content['status'] = 0
                content['payload'] = 'id有誤！'
                content['errmsg'] = ''
        except Exception as e:
            content['status'] = 0
            content['errmsg'] = str(e)
            content['payload'] = []

    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def CustomInfo(request):
    content = {"payload": [], "status": 1, "errmsg": ""}
    """
    客戶信息接口：\n
    1. post參數： c_name:客戶名稱， c_name_short:客戶de名縮寫， c_num: 客戶代碼， c_category：客戶類別， c_factory：客戶廠區\n
    2. get參數： search：搜索關鍵字  page：分頁數數（默認20頁）不傳參數不分頁\n
    """
    if request.method == 'GET':
        try:
            search = request.GET.get("search", None)
            page_num = request.GET.get("page", None)
            import customer.functions as fun
            if search:
                if '*' in search:
                    sp = str(search).split('*')
                    if '' in sp:
                        sp = sp[:-1]
                    resQ = fun.comb(sp)
                    ss = 'models.TbCustomInfo.objects.filter(delete_flag=1)' + resQ
                    res = eval(ss)
                elif '*' not in search:
                    res = models.TbCustomInfo.objects.filter(delete_flag=1).filter(Q(c_name__contains=search) |
                                                                                   Q(c_name_short__contains=search) | Q(
                        c_num__contains=search) |
                                                                                   Q(c_type__contains=search) | Q(
                        c_site__contains=search))
            else:
                res = models.TbCustomInfo.objects.filter(delete_flag=1).order_by('-id')
            if page_num:
                page_class = Paginator(res.values(), 20)
            else:
                page_class = Paginator(res.values(), len(res) + 1)
                page_num = 1

            select_data = page_class.page(page_num)  # 第n页中的内容
            content["payload"] = {"data": [], "page": {}}  # 定义payload的输出格式
            if select_data:  # 循环输出第n页中的内容
                for i in select_data:
                    # 變換時間格式
                    i['create_time'] = i['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                    i['modify_time'] = i['modify_time'].strftime("%Y-%m-%d %H:%M:%S")
                    content['payload']['data'].append(i)
                content["payload"]["page"] = {'count': page_class.count, 'page': int(page_num),
                                              'page_number': page_class.page_range[-1]}
        except Exception as e:
            content['status'] = 0
            content['errmsg'] = str(e)
            content['payload'] = []

    if request.method == 'POST':
        try:
            # post提交获取参数
            c_name = request.POST.get('c_name')
            c_name_short = request.POST.get('c_name_short')
            c_num = request.POST.get('c_num')
            c_type = request.POST.get('c_type')
            c_site = request.POST.get('c_site')
            create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 创建时间
            if c_name or c_name_short or c_num or c_type or c_site:
                models.TbCustomInfo.objects.create(c_name=c_name, c_name_short=c_name_short, c_num=c_num,
                                                   c_type=c_type, c_site=c_site, create_time=create_time,
                                                   modify_time=create_time, delete_flag=1)
                content['status'] = 1
                content['payload'] = '創建成功！'
                content['errmsg'] = ''
        except Exception as e:
            content['status'] = 0
            content['errmsg'] = str(e)
            content['payload'] = []

    return content


# Author: Asa
# Time: 2017-12-14
# 上传文件

@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def UploadFilepk(request, pk):
    content = {"payload": [], "status": 1, "errmsg": ""}
    if request.method == 'DELETE':
        try:
            if pk:
                id_in = models.TbDrawingFile.objects.filter(id=pk).values('id')[0]['id']
                if id_in:
                    f_path = models.TbDrawingFile.objects.get(id=id_in).file_path  # 数据库里面获取存放路径
                    absolute_path = os.path.join(settings.MEDIA_ROOT + f_path)  # 拼凑成绝对路径
                    # 先根据数据库的存放路径来删除文件，再删除数据库的数据
                    if os.path.exists(absolute_path):
                        os.remove(absolute_path)
                        models.TbDrawingFile.objects.get(id=id_in).delete()
                    else:
                        models.TbDrawingFile.objects.get(id=id_in).delete()
                    content['payload'] = '文件刪除成功！'
                    content['errmsg'] = ''
                    content['status'] = 1
        except Exception as e:
            content['errmsg'] = str(e) + ' --> Please check your id.'
            content['status'] = 0
            content['payload'] = []
    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def UploadFile(request):
    content = {"payload": [], "status": 1, "errmsg": ""}
    """
    上传文件接口：\n
    post方法： file_name:选择上传文件  file_type: 0代表图纸文件， 1代表附件(必须输入， 不输入不能上传)\n
    支持解压的文件有zip 和 rar 不是这两种的文件将会以文件的形式上传
    """
    if request.method == 'GET':
        try:
            data = models.TbDrawingFile.objects
            for i in data.values():
                i['create_time'] = (i['create_time']).strftime("%Y-%m-%d %H:%M:%S")
                content['payload'].append(i)
            content['status'] = 1
            content['errmsg'] = ''
        except Exception as e:
            content['status'] = 0
            content['errmsg'] = str(e)
            content['payload'] = []

    if request.method == 'POST':
        file_pdf_rar = ['pdf', 'rar', 'zip']
        file_pdf = ['pdf']
        file_rar = ['rar', 'zip']  # 解压这两种文件
        list_size = {}  # 放解压的结果
        kp = []
        try:
            uploader = request.user.username + "(" + request.user.last_name + ")"  # 获取当前登陆用户名
            data = request.data  # 获取上传数据
            file_type = data['file_type']  # 0为图纸文件， 1 为附件
            f_name = request.FILES.getlist('file_name')  # 接受post的多个文件
            if f_name and file_type:  # 必须输入要上传的文件和文件类型
                if int(file_type) == 0:  # 文件
                    for name in f_name:  # 遍历  写入指定目录
                        spfile = str(name).split('.')
                        # 讓pdf和壓縮包通過
                        if spfile[-1] in file_pdf_rar:
                            new_name = str(uuid.uuid1()) + '.' + spfile[-1]
                            file_origin_path = os.path.join(settings.MEDIA_ROOT, settings.DRAWING_PATH)  # 文件路径
                            file_path = os.path.join(settings.DRAWING_PATH, new_name)  # 数据库存放文件路径
                            create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 创建时间
                            file_origin_name = file_origin_path + new_name
                            with open(file_origin_name, 'wb') as flhd:  # 写入
                                flhd.write(name.read())
                                flhd.close()

                            if file_origin_name.split('.')[-1] in file_pdf:  # 文件添加
                                file_size = os.path.getsize(file_origin_name)

                                mk = models.TbDrawingFile.objects.create(file_name=name, file_size=file_size,
                                                                         file_path=file_path,
                                                                         uploader=uploader, create_time=create_time,
                                                                         file_type=file_type)

                                all_info = {'id': int(mk.id), 'file_name': str(mk.file_name),
                                            'file_size': int(mk.file_size),
                                            'file_type': int(mk.file_type), 'upload_time': str(mk.create_time),
                                            'uploader': str(mk.uploader), 'url': str(mk.file_path),
                                            'file_version': mk.file_version}
                                kp.append(all_info)
                                content['payload'] = kp
                                content['status'] = 1
                                content['errmsg'] = ''
                            elif file_origin_name.split('.')[-1] in file_rar:  # 压缩包添加
                                f, k, ln, no_pdf = fun.un_file(file_origin_name, file_origin_path,
                                                               file_origin_name.split('.')[-1])
                                # 解压函数里面判断pdf的返回值
                                if no_pdf == 1:
                                    list_size.update(k)  # 收集文件的大小
                                    for ke, va in k.items():
                                        m = models.TbDrawingFile.objects.create(file_name=ke, file_size=va,
                                                                                file_path=settings.DRAWING_PATH + f[ke],
                                                                                uploader=uploader,
                                                                                create_time=create_time,
                                                                                file_type=file_type)

                                        all_info = {'id': int(m.id), 'file_name': str(m.file_name),
                                                    'file_size': int(m.file_size),
                                                    'file_type': int(m.file_type), 'upload_time': str(m.create_time),
                                                    'uploader': str(m.uploader), 'url': str(m.file_path)}
                                        kp.append(all_info)
                                    content['payload'] = kp
                                    content['status'] = 1
                                    content['errmsg'] = ''

                                else:
                                    content['payload'] = []
                                    content['status'] = 0
                                    content['errmsg'] = '文件格式錯誤，請重新上傳文件！'
                        else:
                            content['status'] = 0
                            content['payload'] = []
                            content['errmsg'] = '文件只允许上传pdf或者pdf的压缩包！'
                if int(file_type) == 1:  # 附件
                    for name in f_name:  # 遍历  写入指定目录
                        spfile = str(name).split('.')
                        new_name = str(uuid.uuid1()) + '.' + spfile[-1]
                        file_origin_path = os.path.join(settings.MEDIA_ROOT, settings.DRAWING_PATH)  # 文件路径
                        file_path = os.path.join(settings.DRAWING_PATH, new_name)  # 数据库存放文件路径
                        create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 创建时间
                        file_origin_name = file_origin_path + new_name
                        with open(file_origin_name, 'wb') as flhd:  # 写入
                            flhd.write(name.read())
                            flhd.close()
                        # 添加文件
                        if file_origin_name.split('.')[-1] not in file_rar:
                            file_size = os.path.getsize(file_origin_name)
                            mk = models.TbDrawingFile.objects.create(file_name=name, file_size=file_size,
                                                                     file_path=file_path,
                                                                     uploader=uploader, create_time=create_time,
                                                                     file_type=file_type)

                            all_info = {'id': int(mk.id), 'file_name': str(mk.file_name),
                                        'file_size': int(mk.file_size),
                                        'file_type': int(mk.file_type), 'upload_time': str(mk.create_time),
                                        'uploader': str(mk.uploader), 'url': str(mk.file_path)}
                            kp.append(all_info)
                            content['payload'] = kp
                            content['status'] = 1
                            content['errmsg'] = ''
                        # 添加压缩包
                        elif file_origin_name.split('.')[-1] in file_rar:  # 压缩包添加
                            f, k, ln = fun.un_file_notype(file_origin_name, file_origin_path,
                                                          file_origin_name.split('.')[-1])
                            # 解压函数里面判断pdf的返回值
                            list_size.update(k)  # 收集文件的大小
                            for ke, va in k.items():
                                m = models.TbDrawingFile.objects.create(file_name=ke, file_size=va,
                                                                        file_path=settings.DRAWING_PATH + f[ke],
                                                                        uploader=uploader,
                                                                        create_time=create_time,
                                                                        file_type=file_type)

                                all_info = {'id': int(m.id), 'file_name': str(m.file_name),
                                            'file_size': int(m.file_size),
                                            'file_type': int(m.file_type), 'upload_time': str(m.create_time),
                                            'uploader': str(m.uploader), 'url': str(m.file_path)}
                                kp.append(all_info)

                            content['payload'] = kp
                            content['status'] = 1
                            content['errmsg'] = ''
                        else:
                            content['status'] = 0
                            content['payload'] = []
                            content['errmsg'] = '文件格式錯誤，請重新上傳文件！'
            else:
                content['status'] = 0
                content['payload'] = []
                content['errmsg'] = '文件名或着文件类型错误！'
        except Exception as e:
            content['status'] = 0
            content['errmsg'] = str(e)
            content['payload'] = []

    return content


# =====================================================================
@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def CustomerPaperpk(request, pk):
    content = {"payload": {}, "status": 1, "errmsg": ""}
    if request.method == 'GET':
        """
        条件：pk 和  confirm的值     
        """
        if pk:
            co = request.GET.get('confirm')
            status = request.GET.get("status", None)
            try:  # 找客户图纸
                if co != None and pk != None:
                    # cps = models.TbCustomerPaper.objects.filter(id=int(pk)).filter(c_confirm__gte=int(co)).values()
                    cps1 = models.TbCustomerPaper.objects.filter(id=int(pk)).filter(c_confirm__gte=int(co)).values()
                    cps2 = models.TbCustomerPaper.objects.filter(id=int(pk)).filter(c_confirm=-1).values()

                    if cps1:
                        cps = cps1
                    elif cps2:
                        cps = cps2
                    else:
                        content['payload'] = []
                        content['status'] = 0
                        content['errmsg'] = 'please checkout p_confirm.'

                    cppid = cps[0]['copy_id']

                    v_num = models.TbCustomerPaper.objects.filter(id__lte=int(pk), copy_id=int(cppid),
                                                                 c_confirm__gte=2).values('copy_id')
                    if cps1:
                        if len(cps1):
                            cp = cps1[0]
                            ct_id = models.TbCutterType.objects.filter(cutter_type=cp['p_name']).values()
                            # 修改不符合字段
                            cp['valid'] = bool(cp['valid'])
                            cp['enabled'] = bool(cp['enabled'])
                            cp['create_time'] = cp['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                            cp['modify_time'] = cp['modify_time'].strftime("%Y-%m-%d %H:%M:%S")
                            cp['upload_time'] = cp['upload_time'].strftime("%Y-%m-%d %H:%M:%S")
                            cp['customer_info'] = cp.pop('customer_info_id')
                            cp['cutter_type_id'] = ct_id[0]['id']
                            cp['cutter_type'] = ct_id[0]['cutter_type']
                            # cp['cutter_type'] = cp.pop('p_name')
                            # cp['version'] =
                            # cp['next_version'] = int(cp['version']) + 1  # 前台接的是next_version
                            content['payload'] = cp
                            content['payload']['file'] = []
                            # return content
                    elif cps2:
                        if len(cps2):
                            cp = cps2[0]
                            ct_id = models.TbCutterType.objects.filter(cutter_type=cp['p_name']).values()
                            # 修改不符合字段
                            cp['valid'] = bool(cp['valid'])
                            cp['enabled'] = bool(cp['enabled'])
                            cp['create_time'] = cp['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                            cp['modify_time'] = cp['modify_time'].strftime("%Y-%m-%d %H:%M:%S")
                            cp['upload_time'] = cp['upload_time'].strftime("%Y-%m-%d %H:%M:%S")
                            cp['customer_info'] = cp.pop('customer_info_id')
                            # cp['cutter_type_id'] = cp.pop('p_name')
                            cp['cutter_type_id'] = ct_id[0]['id']
                            cp['cutter_type'] = ct_id[0]['cutter_type']
                            # cp['version'] = int(cp['version']) + 1
                            # cp['next_version'] = cp['version']  # 前台接的是next_version
                            content['payload'] = cp
                            content['payload']['file'] = []
                            # return content
                            # vsesion 2018/03/28
                            #  变更之后，签合完成后才算一个版本
                            # v_num = models.TbCustomerPaper.objects.filter(id__lte=int(pk), copy_id=cp_id,
                            #                                               c_confirm__gte=2).values('copy_id')
            except Exception as e:
                content['errmsg'] = str(e) + ' --> check your id,  confirm.'
                content['payload'] = []
                content['status'] = 0
                return content

            try:  # 找文件
                ap = []
                if co != None and pk != None and status == None:
                    # cps = models.TbCustomerPaper.objects.filter(id=int(pk)).filter(c_confirm__gte=int(co))
                    cps1 = models.TbCustomerPaper.objects.filter(id=int(pk)).filter(c_confirm__gte=int(co))
                    cps2 = models.TbCustomerPaper.objects.filter(id=int(pk)).filter(c_confirm=-1)
                    if cps2:
                        cps = cps2
                    else:
                        cps = cps1
                    p = models.TbDrawingFile.objects.filter(customer_id=cps[0].id).values()
                    for k in p:
                        if k["drawing_type_id"]:
                            from files.models import TbDrawingSeal
                            seal_no = TbDrawingSeal.objects.filter(drawing=k["drawing_type_id"]).values_list(
                                "seal__seal_no", flat=1)
                        else:
                            seal_no = []

                        if int(co) == 2:
                            file_name = k['sign_filepath']
                        elif int(co) == 3:
                            file_name = k["seal_filepath"]
                        else:
                            file_name = k["file_path"]
                        k['file_path'] = file_name
                        k['create_time'] = k['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                        k['seal_no'] = seal_no
                        k['dev_type_id'] = k.pop('id_dev_type_id')
                        k['drawing_type'] = k.pop('drawing_type_id')
                        ap.append(k)
                if not status:
                    content['payload']['file'] = ap
            except Exception as e:
                content['errmsg'] = str(e) + ' --> check your customer_id id.'
                content['payload'] = []
                content['status'] = 0

            content['status'] = 1
            return content

    if request.method == 'PUT':
        try:
            # 獲取一般參數
            version = request.POST.get('version')
            reEdit = request.POST.get('reEdit')
            wr = request.POST.get("wr")
            cutter_type_id = request.POST.get('cutter_type_id')
            if cutter_type_id:
                cutter_type_id_res = models.TbCutterType.objects.filter(id=int(cutter_type_id)).values()
                if cutter_type_id_res:
                    p_name = cutter_type_id_res[0]['cutter_type']
                else:
                    content['payload'] = []
                    content['errmsg'] = " 產品類別有誤。"
                    content['status'] = 0
                    return content
            st_site = request.POST.get('st_site')
            custters_spec = request.POST.get('custters_spec')
            case_name = request.POST.get('case_name')
            priority = request.POST.get('priority')
            desc_file = request.POST.get('desc_file')
            alter_cause = request.POST.get('alter_cause')
            alter_front = request.POST.get('alter_front')
            alter_later = request.POST.get('alter_later')
            file_version = request.POST.get('file_version')
            modify_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 创建时间
            c_site = request.POST.get('c_site')
            # 獲取登陸用戶
            cp_all = request.user.username + "(" + request.user.last_name + ")"  # 获取当前登陆用户名
            create_people = request.user.username  # 获取当前登陆用户名
            # 舊版本立即失效
            valid = int(bool(request.POST.get('valid') == "true"))
            copy_id = request.POST.get('copy_id')
            # 客戶資料id
            customer_info = request.POST.get('customer_info')
            # 文件id
            file = request.POST.get('file')  # 手动输入文件id
            file_id = []
            if file:
                file_id = []
                for i in eval(str(file).replace('null', 'None')):
                    file_id.append(i)
            # 確認/草稿
            c_confirm = request.POST.get('c_confirm')  # 确认为1  草稿为0
            # 獲取工作流
            workflow = request.POST.get('workflow', '[]')
            # 生成新的ecn編號
            mid = models.TbCustomerPaper.objects.values_list('id', flat=True).distinct()
            ecn_no = fun.c_ecn(mid)
            if wr:
                wrf_obj = WorkflowApprovalRecord.objects.filter(workflow_record=wr).order_by('-id')[0]
                w = wrf_obj.id
            else:
                w = None
            with transaction.atomic():
                if pk and c_confirm and customer_info:
                    # 找原id的c_confirm
                    pk_id = models.TbCustomerPaper.objects.filter(id=pk)
                    ct = pk_id.values('create_time')[0]['create_time']
                    confirm = pk_id.values('c_confirm')[0]['c_confirm']
                    enabled = pk_id.values('enabled')[0]['enabled']
                    all_data = {1: c_site, 2: version, 3: p_name, 4: st_site, 5: custters_spec, 6: case_name,
                                7: priority, 8: desc_file, 9: modify_time, 10: cp_all, 11: create_people, 12: ecn_no,
                                13: customer_info, 14: file_id, 15: c_confirm, 16: workflow, 17: alter_cause,
                                18: alter_front,
                                19: alter_later, 20: pk_id, 21: ct, 22: confirm, 23: enabled, 24: copy_id,
                                25: valid, 27: reEdit, 28: w,
                                29: request.META["HTTP_X_CSRFTOKEN"]}
                    if int(c_confirm) == 1 and enabled == 1:

                        if int(confirm) >= 2 or int(confirm) == -1:
                            b, n, pdf_list, re_id = fun.c_put(all_data)
                            # 路由籤合
                            if int(c_confirm) == 1 and re_id == 0:
                                file_applicate = request.user
                                from tb_forms.models import TbForms
                                str_id = str(TbForms.objects.filter(sign_type="customer").values_list("id", flat=1)[0])
                                fun.doc_check(b, pdf_list, file_applicate, workflow, n, str_id)
                                # fun.doc_check(b, pdf_list, file_applicate, workflow, n, '381')
                        # 要去除草稿箱的記錄
                        elif int(confirm) == 0:
                            if int(c_confirm) == 1:  # 确认发行后，去除草稿箱的记录#
                                models.TbCustomerPaper.objects.filter(id=pk).update(c_confirm=1)
                            b, n, pdf_list, re_id = fun.c_put(all_data)
                            # 路由籤合
                            if int(c_confirm) == 1 and re_id == 0:
                                file_applicate = request.user
                                from tb_forms.models import TbForms
                                str_id = str(TbForms.objects.filter(sign_type="customer").values_list("id", flat=1)[0])
                                fun.doc_check(b, pdf_list, file_applicate, workflow, n, str_id)
                                # fun.doc_check(b, pdf_list, file_applicate, workflow, n, '381')

                            content['errmsg'] = ''
                            content['status'] = 1
                            content['payload'] = '變更成功！'
                            return content
                    if int(c_confirm) == 0 and enabled == 1:
                        # if int(confirm) == 3 or int(confirm) == 2 or int(confirm) == 0:
                        if int(confirm) >= 2  or int(confirm) == -1:
                            b, n, pdf_list, re_id = fun.c_put(all_data)
                            # 要去除草稿箱的記錄，不能合併
                        elif int(confirm) == 0:
                            if int(c_confirm) == 1:  # 确认发行后，去除草稿箱的记录#
                                models.TbCustomerPaper.objects.filter(id=pk).update(c_confirm=1)
                            b, n, pdf_list, re_id = fun.c_put(all_data)
                            content['errmsg'] = ''
                            content['status'] = 1
                            content['payload'] = '變更成功！'
                            return content
                else:
                    content['errmsg'] = '檢查客戶信息，或者確認/草稿'
                    content['status'] = 0
                    content['payload'] = []
                    return content
        except Exception as e:
            content['errmsg'] = str(e)
            content['status'] = 0
            content['payload'] = []
            return content
    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def CustomerPaper(request):
    content = {"payload": [], "status": 1, "errmsg": ""}
    """
    发行和变更接口
    :param request:
    :return:
                                                                                
    """

    if request.method == 'GET':
        try:
            search = request.GET.get("search", None)
            # for s in searchRes:
            page_num = request.GET.get("page", None)
            # 显示enabled爲1 或者 current 爲1 的值
            if search:
                res = models.TbCustomerPaper.objects.filter(c_confirm__gte=2).filter(
                    Q(enabled=1) | Q(current=1)).filter(
                    Q(ecn_no__contains=search) | Q(version__contains=search) |
                    Q(st_site__contains=search) | Q(version__contains=search) |
                    Q(priority__contains=search) | Q(p_name__contains=search) |
                    Q(definer_name__contains=search) |
                    Q(c_name__contains=search) |
                    Q(c_site__contains=search) | Q(custters_spec__contains=search) |
                    Q(case_name__contains=search))

            else:
                res = models.TbCustomerPaper.objects.filter(c_confirm__gte=2).filter(
                    Q(enabled=1) | Q(current=1)).order_by('-id')

            if page_num:
                page_class = Paginator(res.values(), 20)
            else:
                page_class = Paginator(res.values(), len(res) + 1)
                page_num = 1
            select_data = page_class.page(page_num)  # 第n页中的内容
            content["payload"] = {"data": [], "page": {}}  # 定义payload的输出格式
            if select_data:  # 循环输出第n页中的内容
                for i in select_data:
                    valid_c = fun.bool_turn(i, 'valid')
                    en = fun.bool_turn(i, 'enabled')
                    kk = []
                    file_all = models.TbDrawingFile.objects.filter(customer_id=int(i['id']))
                    for k in file_all.values():
                        k['create_time'] = k['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                        k['dev_type_id'] = k.pop('id_dev_type_id')
                        k['drawing_type'] = k.pop('drawing_type_id')
                        kk.append(k)
                    i['customer_info'] = i.pop('customer_info_id')
                    i['cutter_type'] = i.pop('p_name')
                    i['create_time'] = i['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                    i['modify_time'] = i['modify_time'].strftime("%Y-%m-%d %H:%M:%S")
                    i['valid'] = valid_c
                    i['enabled'] = en
                    i['file'] = kk
                    content['payload']['data'].append(i)
            content["payload"]["page"] = {'count': page_class.count, 'page': int(page_num),
                                          'page_number': page_class.page_range[-1]}

        except Exception as e:
            content['status'] = 0
            content['errmsg'] = str(e)
            content['payload'] = []

    if request.method == 'POST':
        """
        c_confirm： 确认为1 草稿为0  file：文件id(字符串或者数组)  
        draw_type_id:图纸类别 {id:类型}必须不输入将不能提交其他信息
        """
        try:
            # 獲取一般參數
            c_site = request.POST.get('c_site')
            version = request.POST.get('version')
            cutter_type_id = request.POST.get('cutter_type_id')
            if cutter_type_id:
                cutter_type_id_res = models.TbCutterType.objects.filter(id=int(cutter_type_id)).values()
                if cutter_type_id_res:
                    p_name = cutter_type_id_res[0]['cutter_type']
                else:
                    content['payload'] = []
                    content['errmsg'] = " 產品類別有誤。"
                    content['status'] = 0
                    return content
            st_site = request.POST.get('st_site')
            custters_spec = request.POST.get('custters_spec')
            case_name = request.POST.get('case_name')
            priority = request.POST.get('priority')
            desc_file = request.POST.get('desc_file')
            file_version = request.POST.get('file_version')
            create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 创建时间
            # 獲取登陸用戶
            cc = request.user.username + "(" + request.user.last_name + ")"  # 获取当前登陆用户名
            create_people = request.user.username  # 获取当前登陆用户名
            # 生成ecn編號
            mid = models.TbCustomerPaper.objects.values_list('id', flat=True).distinct()
            ecn_no = fun.c_ecn(mid)
            # 獲取客戶資料
            customer_info = request.POST.get('customer_info')
            # 獲取文件id
            file = request.POST.get('file')  # 手动输入文件id
            # 確認/草稿
            c_confirm = request.POST.get('c_confirm')  # 确认为1  草稿为0
            # 獲取籤合的工作流
            workflow = request.POST.get('workflow', '[]')

            # 2018/4/19
            file_id = []
            if file:
                file_id = []
                for i in eval(str(file).replace('null', 'None')):
                    file_id.append(i)

            # 2018/03/28  刀具规格不能重复
            # res_list = []
            res = models.TbCustomerPaper.objects.all().values('custters_spec').distinct()
            if res:
                res_cs = list(res)
                for i in res_cs:
                    # res_list.append(i['custters_spec'])
                    if i['custters_spec'] == custters_spec:
                        content['payload'] = []
                        content['errmsg'] = '刀具規格重複.'
                        content['status'] = 0
                        return content

            all_data = {1: c_site, 2: version, 3: p_name, 4: st_site, 5: custters_spec, 6: case_name,
                        7: priority, 8: desc_file, 9: create_time, 10: cc, 11: create_people, 12: ecn_no,
                        13: customer_info, 14: file_id, 15: c_confirm, 16: workflow, 17: file_version}

            # 开始post
            with transaction.atomic():
                # if c_confirm and customer_info and file:
                if c_confirm and customer_info:
                    if file:
                        # 發行
                        if int(c_confirm) == 1:
                            a, pdf_list, n = fun.c_post(all_data)
                            if int(all_data[15]) == 1:
                                # 路由籤合
                                file_applicate = request.user
                                # 229 上用要查找提交
                                from tb_forms.models import TbForms
                                str_id = str(TbForms.objects.filter(sign_type="customer").values_list("id", flat=1)[0])
                                fun.doc_check(a, pdf_list, file_applicate, workflow, n, str_id)
                                # 10.129.4.97 上用此提交
                                # fun.doc_check(a, pdf_list, file_applicate, workflow, n, '381')
                                content['payload'] = "創建成功！"
                        # 存草稿
                        if int(c_confirm) == 0:
                            a, pdf_list, n = fun.c_post(all_data)
                            content['payload'] = "草稿保存成功！"
                        content['errmsg'] = ''
                        content['status'] = 1
                    else:
                        # 發行
                        if int(c_confirm) == 1:
                            a, pdf_list, n = fun.c_post(all_data)
                            if int(all_data[15]) == 1:
                                content['payload'] = []
                                content['errmsg'] = '請上傳文件！'
                                content['status'] = 0
                                # # 路由籤合
                                file_applicate = request.user
                                from tb_forms.models import TbForms
                                str_id = str(TbForms.objects.filter(sign_type="customer").values_list("id", flat=1)[0])
                                fun.doc_check(a, pdf_list, file_applicate, workflow, n, str_id)
                                # fun.doc_check(a, pdf_list, file_applicate, workflow, n, '381')
                        # 存草稿
                        if int(c_confirm) == 0:
                            a, pdf_list, n = fun.c_post(all_data)
                            content['payload'] = "草稿保存成功！"
                            content['errmsg'] = ''
                            content['status'] = 1
        except Exception as e:
            content['payload'] = []
            content['errmsg'] = str(e)
            content['status'] = 0
    return content


# =======================================================================

@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def Version(request, pk):
    content = {"payload": [], "status": 1, "errmsg": ""}
    """
    历史版本 接口
    :param request:
    :param v:
    :return:
    """
    if request.method == 'GET':
        if pk:
            cp_id = models.TbCustomerPaper.objects.filter(id=int(pk), c_confirm__gte=2).values('copy_id')[0]['copy_id']
            data_custom = models.TbCustomerPaper.objects.filter(copy_id=cp_id, c_confirm__gte=2).exclude(
                id=int(pk)).order_by('-id')
            for i in data_custom.values():
                kk = []
                file_all = models.TbDrawingFile.objects.filter(customer_id=int(i['id']))
                for k in file_all.values():
                    k['create_time'] = k['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                    k['dev_type_id'] = k.pop('id_dev_type_id')
                    k['drawing_type'] = k.pop('drawing_type_id')
                    kk.append(k)
                valid_c = fun.bool_turn(i, 'valid')
                en = fun.bool_turn(i, 'enabled')
                i['valid'] = valid_c
                i['enabled'] = en
                i['customer_info'] = i.pop('customer_info_id')
                i['create_time'] = i['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                i['modify_time'] = i['modify_time'].strftime("%Y-%m-%d %H:%M:%S")
                i.pop('upload_time')
                i['file'] = kk
                content['payload'].append(i)
            content['errmsg'] = ''
            content['status'] = 1
        else:
            content['payload'] = []
            content['errmsg'] = 'check your id,'
            content['status'] = 0

    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def Draftpk(request, pk):
    content = {"payload": [], "status": 1, "errmsg": ""}
    if request.method == 'GET':
        create_people = request.user.username  # 获取当前登陆用户名
        res = models.TbCustomerPaper.objects.filter(id=int(pk), c_confirm=0, create_people=create_people)
        for i in res.values():
            kk = []
            file_all = models.TbDrawingFile.objects.filter(customer_id=int(i['id']))
            for k in file_all.values():
                k['create_time'] = k['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                k['dev_type_id'] = k.pop('id_dev_type_id')
                k['drawing_type'] = k.pop('drawing_type_id')
                k['file_path'] = '/' + k['file_path']
                kk.append(k)
            valid_c = fun.bool_turn(i, 'valid')
            en = fun.bool_turn(i, 'enabled')
            i['valid'] = valid_c
            i['enabled'] = en
            i['customer_info'] = i.pop('customer_info_id')
            i['create_time'] = i['create_time'].strftime("%Y-%m-%d %H:%M:%S")
            i['modify_time'] = i['modify_time'].strftime("%Y-%m-%d %H:%M:%S")
            i.pop('upload_time')
            i['file'] = kk
            content['payload'] = i
        content['status'] = 1
        content['errmsg'] = ''

    if request.method == 'DELETE':
        try:
            models.TbDrawingFile.objects.filter(customer_id=pk).all().delete()
            fb = models.TbCustomerPaper.objects.filter(id=pk)
            if fb.values('c_confirm'):
                for i in fb.values('c_confirm'):
                    for k, v in i.items():
                        if int(v) == 0:
                            fb.delete()
                            content['payload'] = '刪除成功！'
                            content['errmsg'] = ''
                            content['status'] = 1
                        else:
                            content['errmsg'] = 'id有誤！'
                            content['status'] = 0
                            content['payload'] = ''

        except Exception as e:
            content['payload'] = []
            content['errmsg'] = str(e)
            content['status'] = 0
    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def Draft_sp(request):
    content = {"payload": [], "status": 1, "errmsg": ""}
    if request.method == 'GET':
        try:
            search = request.GET.get("search", None)
            page_num = request.GET.get("page", None)
            create_people = request.user.username  # 获取当前登陆用户名
            if search:
                res = models.TbCustomerPaper.objects.filter(c_confirm=0).filter(create_people=create_people).filter(
                    Q(ecn_no__contains=search) | Q(version__contains=search) |
                    Q(case_name__contains=search) | Q(c_type__contains=search) |
                    Q(version__contains=search) | Q(priority__contains=search) |
                    Q(c_name__contains=search) | Q(c_site__contains=search))
            else:
                res = models.TbCustomerPaper.objects.filter(c_confirm=0).filter(create_people=create_people).order_by(
                    '-id')
            if page_num:
                page_class_k = Paginator(res.values(), 20)
            else:
                page_class_k = Paginator(res.values(), len(res) + 1)
                page_num = 1
            select_data_k = page_class_k.page(page_num)  # 第n页中的内容
            content["payload"] = {"data": [], "page": {}}  # 定义payload的输出格式
            if select_data_k:  # 循环输出第n页中的内容
                for i in select_data_k:
                    kk = []
                    fi = models.TbDrawingFile.objects.filter(customer_id=int(i['id']))
                    for k in fi.values():
                        k['create_time'] = k['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                        k['dev_type_id'] = k.pop('id_dev_type_id')
                        k['drawing_type'] = k.pop('drawing_type_id')
                        k['file_path'] = '/' + k['file_path']
                        kk.append(k)
                    valid_c = fun.bool_turn(i, 'valid')
                    en = fun.bool_turn(i, 'enabled')
                    i['valid'] = valid_c
                    i['enabled'] = en
                    i['customer_info'] = i.pop('customer_info_id')
                    i['create_time'] = i['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                    i['modify_time'] = i['modify_time'].strftime("%Y-%m-%d %H:%M:%S")
                    i.pop('upload_time')
                    i['file'] = kk
                    content['payload']['data'].append(i)
            content["payload"]["page"] = {'count': page_class_k.count, 'page': int(page_num),
                                          'page_number': page_class_k.page_range[-1]}
        except Exception as e:
            content['status'] = 0
            content['errmsg'] = str(e)
            content['payload'] = []

    return content


# ================================================================
@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def Project_paperpk(request, pk):
    content = {"payload": {}, "status": 1, "errmsg": ""}
    if request.method == 'GET':
        """
        条件：copy_id=id  c_confirm=1
        """
        pc = request.GET.get('confirm')
        if pk:
            cd = []
            try:  # 找工程图纸
                # cps = models.TbProjectPaper.objects.filter(id=int(pk)).filter(p_confirm__gte=int(pc)).values()
                cps1 = models.TbProjectPaper.objects.filter(id=int(pk)).filter(p_confirm__gte=int(pc)).values()
                cps2 = models.TbProjectPaper.objects.filter(id=int(pk)).filter(p_confirm=-1).values()
                if cps1:
                    cps = cps1
                elif cps2:
                    cps = cps2
                else:
                    content['payload'] = []
                    content['status'] = 0
                    content['errmsg'] = 'please checkout p_confirm.'

                cppid = cps[0]['id_copy']
                ct = cps[0]['custters_spec']
                cutter_type_list = []
                vvv = models.TbCustomerPaper.objects.all().values()
                for i in list(vvv):
                    cutter_type_list.append(i['custters_spec'])
                com_id = []
                if ct in cutter_type_list:
                    cs = models.TbCustomerPaper.objects.filter(custters_spec=ct).all().values()
                else:
                    cs = None
                if cs:
                    for k in list(cs):
                        com_id.append(k['id'])
                    cres = max(com_id)
                else:
                    cres = ''
                # vsesion 2018/03/28
                #  变更之后，签合完成后才算一个版本
                v_num = models.TbProjectPaper.objects.filter(id__lte=int(pk), id_copy=int(cppid),
                                                             p_confirm__gte=2).values('id_copy')

                if len(cps):
                    cp = cps[0]
                    findP_confirm = cps[0]['p_confirm']
                    if findP_confirm == -1:
                        n_version = int(cp['version'])
                    else:
                        n_version = int(cp['version']) + 1
                    cp['related_customer'] = cres
                    # cp['version'] = int(cp['version']) + 1
                    # cp['next_version'] = len(v_num) + 1
                    cp['next_version'] = n_version
                    cp['valid'] = bool(cp['valid'])
                    cp['enabled'] = bool(cp['enabled'])
                    cp['copy_id'] = cp.pop('id_copy')
                    cp['stage_type_id'] = cp.pop('id_stage_type')
                    cp['cutter_type_id'] = cp.pop('id_cutter_type')
                    cp['dev_type_id'] = cp.pop('id_dev_type')
                    cp['drawing_type_id'] = cp.pop('id_drawing_type')
                    cp['create_time'] = cp['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                    cp['modify_time'] = cp['modify_time'].strftime("%Y-%m-%d %H:%M:%S")
                    cp['upload_time'] = cp['upload_time'].strftime("%Y-%m-%d %H:%M:%S")
                    cp['p_category'] = cp.pop('project_name')
                    content['payload'] = cp
            except Exception as e:
                content['errmsg'] = str(e) + ' --> check your cop_id,  no confirm.'
            try:  # 找工程图纸对应的文件
                cp1 = models.TbProjectPaper.objects.filter(id=int(pk)).filter(p_confirm__gte=int(pc))
                cp2 = models.TbProjectPaper.objects.filter(id=int(pk)).filter(p_confirm=-1)
                if cp1:
                    if cp1 == []:
                        cd = []
                    elif cp1 != []:
                        cp_id = cp1.values('id')[0]['id']
                        cd = models.TbDrawingFile.objects.filter(project_id=cp_id)
                elif cp2:
                    if cp2 == []:
                        cd = []
                    elif cp2 != []:
                        cp_id = cp2.values('id')[0]['id']
                        cd = models.TbDrawingFile.objects.filter(project_id=cp_id)

            except Exception as e:
                content['errmsg'] = str(e) + ' --> check your project_id id.'
            else:
                if cd != []:
                    kk = []
                    for k in cd.values():
                        if k['drawing_type_id'] != None:
                            dt = models.TbDrawing.objects.filter(id=k['drawing_type_id']).values('drawing_type')[0][
                                'drawing_type']
                        else:
                            dt = None
                        if k['id_dev_type_id'] != None:
                            dv = models.TbTypeDevice.objects.filter(id=k['id_dev_type_id']).values('dev_type')[0][
                                'dev_type']
                        else:

                            dv = None
                        if k["drawing_type_id"]:
                            from files.models import TbDrawingSeal
                            seal_no = TbDrawingSeal.objects.filter(drawing=k["drawing_type_id"]).values_list(
                                "seal__seal_no", flat=1)
                        else:
                            seal_no = []

                        if int(pc) == 2:
                            file_name = k['sign_filepath']
                        elif int(pc) == 3:
                            file_name = k["seal_filepath"]
                        else:
                            file_name = k["file_path"]

                        k['create_time'] = k['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                        k['project'] = k.pop('project_id')
                        k['drawing_type'] = dt
                        k['drawing_type_id'] = k.pop('drawing_type_id')
                        k['dev_type'] = dv
                        k['dev_type_id'] = k.pop('id_dev_type_id')
                        k['drawing_type'] = k.pop('drawing_type_name')
                        k['seal_no'] = seal_no
                        k['file_path'] = file_name
                        kk.append(k)
                    content['payload']['file'] = kk
            content['errmsg'] = ''
            content['status'] = 1
        else:
            content['status'] = 0
            content['errmsg'] = '請檢查id!'
            content['payload'] = []

    if request.method == 'PUT':
        try:
            with transaction.atomic():
                version = request.POST.get('version')
                if version.isdigit():
                    pass
                else:
                    content['payload'] = []
                    content['errmsg'] = " 版本號應該是數字！"
                    content['status'] = 0
                    return content
                reEdit = request.POST.get('reEdit')
                wr = request.POST.get("wr")
                st_site = request.POST.get('st_site')
                definer_name = request.POST.get('definer_name')
                project_name = request.POST.get('p_category')
                p_type = request.POST.get('p_type')
                custters_spec = request.POST.get('custters_spec')
                case_name = request.POST.get('case_name')
                secrecy_level = request.POST.get('secrecy_level')
                case_no = request.POST.get('case_no')
                priority = request.POST.get('priority')
                desc_file = request.POST.get('desc_file')
                alter_cause = request.POST.get('alter_cause')
                alter_front = request.POST.get('alter_front')
                alter_later = request.POST.get('alter_later')
                file_version = request.POST.get('file_version')
                create_time = str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))  # 创建时间

                # 獲取工作流
                workflow = request.POST.get('workflow', '[]')
                # 轉換
                valid = int(bool(request.POST.get('valid') == "true"))
                # 获取当前登陆用户名
                create_people = request.user.username
                # 創建ecn編號
                mid = models.TbProjectPaper.objects.values_list('id', flat=True).distinct()
                ecn_no = fun.p_ecn(mid)
                # 獲取文件信息
                file = request.POST.get('file')  # 手动输入文件id
                # 確認/ 草稿
                p_confirm = request.POST.get('p_confirm')  # 确认为1  草稿为0
                # 產品階段
                pt_id = request.POST.get('stage_type_id')  # 通过提交的id获取相应的值  产品阶段
                if pt_id:
                    stage_type = models.TbProdectStarge.objects.filter(id=pt_id).values('product_stage')
                    if stage_type:
                        ps = str(stage_type[0]['product_stage'])
                    else:
                        ps = None
                # 道具規格
                kf_id = request.POST.get('cutter_type_id')  # 刀具类型
                if kf_id:
                    knife_type = models.TbCutterType.objects.filter(id=kf_id).values('cutter_type')
                    if knife_type:
                        kt = str(knife_type[0]['cutter_type'])
                    else:
                        kt = None
                # 处理文件
                file_id = []
                for i in eval((str(file).replace('null', 'None'))):
                    file_id.append(i)
                # 立即失效
                # if valid:
                #     # 如果valid爲1,修改上一版本圖紙的 enabled 爲0
                #     copy_id = request.POST.get('copy_id')
                #     if copy_id:
                #         models.TbProjectPaper.objects.filter(id_copy=copy_id, p_confirm__gte=2).update(enabled=0)
                # 機密等級
                if secrecy_level != None:
                    secrecy_level = secrecy_level
                else:
                    secrecy_level = None
                # 获取p_confirm的值
                confirm = models.TbProjectPaper.objects.filter(id=int(pk)).values('p_confirm')[0]['p_confirm']
                enabled = models.TbProjectPaper.objects.filter(id=int(pk)).values('enabled')[0]['enabled']
                if wr:
                    wrf_obj = WorkflowApprovalRecord.objects.filter(workflow_record=wr).order_by('-id')[0]
                    w = wrf_obj.id
                else:
                    w = None
                all_data = {1: version, 2: st_site, 3: definer_name, 4: project_name, 5: p_type, 6: custters_spec,
                            7: case_name, 8: secrecy_level, 9: case_no, 10: priority, 11: desc_file, 12: alter_cause,
                            13: alter_front, 14: alter_later, 15: valid, 16: create_people, 17: ecn_no, 18: file_id,
                            19: p_confirm, 20: pt_id, 21: ps, 22: kf_id, 23: kt, 24: secrecy_level, 25: confirm,
                            26: enabled,
                            27: pk, 28: file_version, 29: reEdit, 30:w, 31: request.META["HTTP_X_CSRFTOKEN"]}

                if int(p_confirm) == 1 and enabled == 1:
                    if valid:
                        # 如果valid爲1,修改上一版本圖紙的 enabled 爲0
                        copy_id = request.POST.get('copy_id')
                        if copy_id:
                            models.TbProjectPaper.objects.filter(id_copy=copy_id, p_confirm__gte=2).update(enabled=0)
                    if (pk and int(confirm) >= 2)  or (pk and int(confirm) == -1):
                        a, pdf_list, n, em, re_id = fun.p_put(all_data)
                        if int(p_confirm) == 1 and re_id == 0:
                            # 从新排序
                            pl = []
                            pdf_list_new = []
                            nn = []
                            for i in pdf_list:
                                pl.append(i['id'])
                            pl.sort()
                            for i in pl:
                                for j in pdf_list:
                                    if int(i) == int(j['id']):
                                        pdf_list_new.append(j)
                                        nn.append(j['href'])

                            file_applicate = request.user
                            from tb_forms.models import TbForms
                            str_id = str(TbForms.objects.filter(sign_type="project").values_list("id", flat=1)[0])
                            fun.doc_check1(a, pdf_list_new, file_applicate, workflow, n, str_id)
                            # fun.doc_check1(a, pdf_list_new, file_applicate, workflow, n, '379')

                        content['errmsg'] = ''
                        content['status'] = 1
                        content['payload'] = "發行成功！"
                    elif pk and confirm == 0:
                        a, pdf_list, n, em, re_id = fun.p_put(all_data)
                        if int(p_confirm) == 1 and re_id == 0:
                            models.TbProjectPaper.objects.filter(id=pk).update(p_confirm=1)  # 草稿箱去除变更记录
                            # 重新排序
                            pl = []
                            pdf_list_new = []
                            nn = []
                            for i in pdf_list:
                                pl.append(i['id'])
                            pl.sort()
                            for i in pl:
                                for j in pdf_list:
                                    if int(i) == int(j['id']):
                                        pdf_list_new.append(j)
                                        nn.append(j['href'])
                            file_applicate = request.user
                            from tb_forms.models import TbForms
                            str_id = str(TbForms.objects.filter(sign_type="project").values_list("id", flat=1)[0])
                            fun.doc_check1(a, pdf_list_new, file_applicate, workflow, n, str_id)
                            # fun.doc_check1(a, pdf_list_new, file_applicate, workflow, n, '379')

                        if em == 'modify success.':
                            content['errmsg'] = ''
                            content['status'] = 1
                            content['payload'] = "發行成功！"
                    else:
                        content['errmsg'] = 'id有誤！'
                        content['status'] = 0
                        content['payload'] = []
                elif int(p_confirm) == 0 and enabled == 1:
                    if valid:
                        # 如果valid爲1,修改上一版本圖紙的 enabled 爲0
                        copy_id = request.POST.get('copy_id')
                        if copy_id:
                            models.TbProjectPaper.objects.filter(id_copy=copy_id, p_confirm__gte=2).update(enabled=0)

                    if (pk and confirm == 3) or (pk and confirm == 2) or (pk and int(confirm) == -1):
                        a, pdf_list, n, em, re_id = fun.p_put(all_data)
                        if em == 'modify success.':
                            content['errmsg'] = "草稿保存成功！"
                            content['status'] = 1
                            content['payload'] = []
                    elif pk and confirm == 0:
                        if p_confirm == 1:  # 草稿箱去除变更记录
                            models.TbProjectPaper.objects.filter(id=pk).update(p_confirm=1)
                        a, pdf_list, n, em = fun.p_put(all_data)
                        if em == 'modify success.':
                            content['errmsg'] = "草稿保存成功！"
                            content['status'] = 1
                            content['payload'] = []
                    else:
                        content['errmsg'] = 'id有誤！'
                        content['status'] = 0
                        content['payload'] = []

        except Exception as e:
            if str(e) == 'division by zero':
                content['errmsg'] = '請輸入圖紙類別！'
                content['payload'] = []
                content['status'] = 0
            else:
                content['payload'] = []
                content['errmsg'] = str(e)
                content['status'] = 0
    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def Project_paper(request):
    """
    工程图纸接口
    :param request:
    :return:
    """
    content = {"payload": [], "status": 1, "errmsg": ""}
    if request.method == 'GET':
        # try:
        search = request.GET.get("search", None)
        page_num = request.GET.get("page", None)
        if search:
            res = models.TbProjectPaper.objects.filter(p_confirm__gte=2).filter(Q(enabled=1) | Q(current=1)).filter(
                Q(ecn_no__contains=search) | Q(definer_name__contains=search) | Q(cutter_type__contains=search) |
                Q(custters_spec__contains=search) | Q(case_name__contains=search) | Q(version__contains=search) |
                Q(priority__contains=search) | Q(st_site__contains=search) | Q(stage_type__contains=search) |
                Q(version__contains=search) | Q(case_no__contains=search))
        else:
            res = models.TbProjectPaper.objects.filter(p_confirm__gte=2).filter(Q(enabled=1) | Q(current=1)).order_by(
                '-id')
        if page_num:
            page_class = Paginator(res.values(), 20)
        else:
            page_class = Paginator(res.values(), len(res) + 1)
            page_num = 1

        select_data = page_class.page(page_num)  # 第n页中的内容
        content["payload"] = {"data": [], "page": {}}  # 定义payload的输出格式
        if select_data:  # 循环输出第n页中的内容
            for i in select_data:
                valid_c = fun.bool_turn(i, 'valid')
                en = fun.bool_turn(i, 'enabled')
                kk = []
                kk_all = models.TbDrawingFile.objects.filter(project_id=i['id'])
                for k in kk_all.values():
                    if k['drawing_type_id'] != None:
                        dt = models.TbDrawing.objects.filter(id=k['drawing_type_id']).values('drawing_type')[0][
                            'drawing_type']
                    else:
                        dt = None
                    if k['id_dev_type_id'] != None:
                        dv = models.TbTypeDevice.objects.filter(id=k['id_dev_type_id']).values('dev_type')[0][
                            'dev_type']
                    else:
                        dv = None
                    k['create_time'] = k['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                    k['project'] = k.pop('project_id')
                    k['drawing_type'] = dt
                    k['drawing_type_id'] = k.pop('drawing_type_id')
                    k['dev_type'] = dv
                    k['dev_type_id'] = k.pop('id_dev_type_id')
                    k['drawing_type'] = k.pop('drawing_type_name')
                    kk.append(k)
                i['valid'] = valid_c
                i['enabled'] = en
                i['create_time'] = i['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                i['modify_time'] = i['modify_time'].strftime("%Y-%m-%d %H:%M:%S")
                i['upload_time'] = i['upload_time'].strftime("%Y-%m-%d %H:%M:%S")
                i['copy_id'] = i.pop('id_copy')
                i['stage_type_id'] = i.pop('id_stage_type')
                i['dev_type_id'] = i.pop('id_dev_type')
                i['drawing_type_id'] = i.pop('id_drawing_type')
                i['cutter_type_id'] = i.pop('id_cutter_type')
                i['file'] = kk
                i['p_category'] = i.pop('project_name')
                content['payload']['data'].append(i)
        content["payload"]["page"] = {'count': page_class.count, 'page': int(page_num),
                                      'page_number': page_class.page_range[-1]}

    if request.method == 'POST':
        """
        c_confirm： 确认为1 草稿为0  file：文件id(字符串或者数组)
        cutter_type_id:道具规格  product_stage_id：产品阶段
        drawing_type_id：图纸类别  dev_type_id：机型
        """
        try:
            version = request.POST.get('version')
            if version.isdigit():
                pass
            else:
                content['payload'] = []
                content['errmsg'] = " 版本號應該是數字！"
                content['status'] = 0
                return content
            st_site = request.POST.get('st_site')
            definer_name = request.POST.get('definer_name')
            project_name = request.POST.get('p_category')
            p_type = request.POST.get('p_type')
            custters_spec = request.POST.get('custters_spec')
            case_name = request.POST.get('case_name')
            case_no = request.POST.get('case_no')
            priority = request.POST.get('priority')
            desc_file = request.POST.get('desc_file')
            create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 创建时间
            secrecy_level = request.POST.get('secrecy_level')
            file = request.POST.get('file')  # 手动输入文件id
            p_confirm = request.POST.get('p_confirm')  # 确认为1  草稿为0
            file_version = request.POST.get('file_version')  # 确认为1  草稿为0
            # 獲取工作流
            workflow = request.POST.get('workflow', '[]')
            create_people = request.user.username  # 获取当前登陆用户名
            cc = request.user.username + "(" + request.user.last_name + ")"  # 获取当前登陆用户名
            mid = models.TbProjectPaper.objects.values_list('id', flat=True).distinct()
            if mid:
                ecn_no = fun.p_ecn(mid)
            else:
                ecn_time = time.strftime('%Y%m%d', time.localtime(time.time()))
                ecn_no = 'ECN_E' + str(ecn_time) + '0001'

            pt_id = request.POST.get('stage_type_id')  # 通过提交的id获取相应的值  产品阶段
            ps = None
            if pt_id:
                stage_type = models.TbProdectStarge.objects.filter(id=pt_id).values('product_stage')
                if stage_type:
                    ps = str(stage_type[0]['product_stage'])

            kf_id = request.POST.get('cutter_type_id')  # 刀具类型
            kt = None
            if kf_id:
                cutter_type = models.TbCutterType.objects.filter(id=kf_id).values('cutter_type')
                if cutter_type:
                    kt = str(cutter_type[0]['cutter_type'])
            file_id = []
            if file:
                file_id = []
                for i in eval(str(file).replace('null', 'None')):
                    file_id.append(i)
            all_data = {1: version, 2: st_site, 3: definer_name, 4: project_name, 5: p_type, 6: custters_spec,
                        7: case_name, 8: secrecy_level, 9: case_no, 10: priority, 11: desc_file,
                        12: cc, 13: create_people, 14: ecn_no, 15: file_id, 16: p_confirm, 17: pt_id, 18: ps,
                        19: kf_id, 20: kt, 21: secrecy_level, 22: file_version,
                        }
            with transaction.atomic():
                if int(p_confirm) == 1:
                    a, pdf_list, n, em = fun.p_post(all_data)
                    pl = []
                    pdf_list_new = []
                    nn = []
                    for i in pdf_list:
                        pl.append(i['id'])
                    pl.sort()
                    for i in pl:
                        for j in pdf_list:
                            if int(i) == int(j['id']):
                                pdf_list_new.append(j)
                                nn.append(j['href'])
                    file_applicate = request.user
                    #  229 上用要查找提交
                    from tb_forms.models import TbForms
                    str_id = str(TbForms.objects.filter(sign_type="project").values_list("id", flat=1)[0])
                    fun.doc_check1(a, pdf_list_new, file_applicate, workflow, n, str_id)
                    # 97 上用此提交
                    # fun.doc_check1(a, pdf_list_new, file_applicate, workflow, n, '379')

                    if em == 'create success.':
                        content['errmsg'] = ''
                        content['status'] = 1
                        content['payload'] = "創建成功！"
                elif int(p_confirm) == 0:
                    a, pdf_list, n, em = fun.p_post(all_data)
                    if em == 'create success.':
                        content['errmsg'] = ''
                        content['status'] = 1
                        content['payload'] = "草稿保存成功！"
        except Exception as e:
            if str(e) == 'division by zero':
                content['errmsg'] = '請輸入圖紙類別！'
                content['payload'] = []
                content['status'] = 0
            else:
                content['payload'] = []
                content['errmsg'] = str(e)
                content['status'] = 0
    return content


# =======================================================================


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def Pro_Version(request, pk):
    content = {"payload": [], "status": 1, "errmsg": ""}
    """
    历史版本 接口
    :param request:
    :param request:
    :param v:
    :return:
    """
    if request.method == 'GET':
        if pk:
            cp_id = models.TbProjectPaper.objects.filter(id=int(pk), p_confirm__gte=2).values('id_copy')[0]['id_copy']
            data_custom = models.TbProjectPaper.objects.all().filter(id_copy=cp_id, p_confirm__gte=2).exclude(
                id=int(pk)).order_by('-id')
            for i in data_custom.values():
                valid_c = fun.bool_turn(i, 'valid')
                en = fun.bool_turn(i, 'enabled')
                file_all = models.TbDrawingFile.objects.filter(project_id=int(i['id']))
                kk = []
                for k in file_all.values():
                    k['create_time'] = k['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                    k['project'] = k.pop('project_id')
                    k['drawing_type_id'] = k.pop('drawing_type_id')
                    k['dev_type_id'] = k.pop('id_dev_type_id')
                    k['drawing_type'] = k.pop('drawing_type_name')
                    kk.append(k)
                i['valid'] = valid_c
                i['enabled'] = en
                i['create_time'] = i['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                i['modify_time'] = i['modify_time'].strftime("%Y-%m-%d %H:%M:%S")
                i['upload_time'] = i['upload_time'].strftime("%Y-%m-%d %H:%M:%S")
                i['copy_id'] = i.pop('id_copy')
                i['stage_type_id'] = i.pop('id_stage_type')
                i['dev_type_id'] = i.pop('id_dev_type')
                i['drawing_type_id'] = i.pop('id_drawing_type')
                i['cutter_type_id'] = i.pop('id_cutter_type')
                i['file'] = kk
                content['payload'].append(i)
            content['errmsg'] = ''
            content['status'] = 1

        else:
            content['payload'] = []
            content['errmsg'] = 'check your id,'
            content['status'] = 0
    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def Pro_Draftpk(request, pk):
    content = {"payload": [], "status": 1, "errmsg": ""}
    try:
        if request.method == 'GET':
            create_people = request.user.username  # 获取当前登陆用户名
            project_all = models.TbProjectPaper.objects.filter(id=pk).filter(p_confirm=0).filter(
                create_people=create_people).values()
            for i in project_all.values():
                valid_c = fun.bool_turn(i, 'valid')
                en = fun.bool_turn(i, 'enabled')
                fi = models.TbDrawingFile.objects.filter(project_id=i['id'])
                kk = []
                for k in fi.values():
                    k['create_time'] = k['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                    k['project'] = k.pop('project_id')
                    k['drawing_type_id'] = k.pop('drawing_type_id')
                    k['dev_type_id'] = k.pop('id_dev_type_id')
                    k['drawing_type'] = k.pop('drawing_type_name')
                    kk.append(k)
                i['valid'] = valid_c
                i['enabled'] = en
                i['create_time'] = i['create_time'].strftime("%Y-%m-%d %H:%M:%S") if i["create_time"] else None
                i['modify_time'] = i['modify_time'].strftime("%Y-%m-%d %H:%M:%S") if i["modify_time"] else None
                i['upload_time'] = i['upload_time'].strftime("%Y-%m-%d %H:%M:%S") if i["upload_time"] else None
                i['copy_id'] = i.pop('id_copy')
                i['stage_type_id'] = i.pop('id_stage_type')
                i['dev_type_id'] = i.pop('id_dev_type')
                i['drawing_type_id'] = i.pop('id_drawing_type')
                i['cutter_type_id'] = i.pop('id_cutter_type')
                i['file'] = kk
                content['payload'] = i
            content['errmsg'] = ''
            content['status'] = 1

        if request.method == 'DELETE':
            models.TbDrawingFile.objects.filter(project_id=pk).all().delete()
            fb = models.TbProjectPaper.objects.filter(id=pk)
            if fb.values('p_confirm'):
                for i in fb.values('p_confirm'):
                    for k, v in i.items():
                        if int(v) == 0:
                            fb.delete()
                            content['payload'] = '刪除成功！'
                            content['errmsg'] = ''
                            content['status'] = 1
                        else:
                            content['errmsg'] = 'id有誤！'
                            content['status'] = 0
            else:
                content['errmsg'] = 'id有誤！'
                content['status'] = 0
    except Exception as e:
        content['payload'] = []
        content['errmsg'] = str(e)
        content['status'] = 0
    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def Pro_Draft_sp(request):
    content = {"payload": [], "status": 1, "errmsg": ""}
    if request.method == 'GET':
        try:
            search = request.GET.get("search", None)
            page_num = request.GET.get("page", None)
            create_people = request.user.username + "(" + request.user.last_name + ")"  # 获取当前登陆用户名
            if create_people:
                create_people = str(create_people).split('(')[0]
            if search:
                res = models.TbProjectPaper.objects.filter(p_confirm=0).filter(create_people=create_people).filter(
                    Q(ecn_no__contains=search) |
                    Q(version__contains=search) | Q(custters_spec__contains=search) |
                    Q(case_name__contains=search) | Q(drawing_type__contains=search) |
                    Q(priority__contains=search) |
                    Q(create_people__contains=search) |
                    Q(case_no__contains=search)).values()
            else:
                res = models.TbProjectPaper.objects.filter(p_confirm=0).filter(
                    create_people=create_people).values().order_by('-id')
            if page_num:
                page_class_k = Paginator(res.values(), 20)
            else:
                page_class_k = Paginator(res.values(), len(res) + 1)
                page_num = 1

            select_data_k = page_class_k.page(page_num)  # 第n页中的内容
            content["payload"] = {"data": [], "page": {}}  # 定义payload的输出格式

            if select_data_k:  # 循环输出第n页中的内容#
                for i in select_data_k:
                    valid_c = fun.bool_turn(i, 'valid')
                    en = fun.bool_turn(i, 'enabled')

                    kk = []
                    fi = models.TbDrawingFile.objects.filter(project_id=int(i['id'])).filter(
                        project__p_confirm=0).filter(project__create_people=create_people)
                    for k in fi.values():
                        k['create_time'] = k['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                        k['project'] = k.pop('project_id')
                        k['drawing_type_id'] = k.pop('drawing_type_id')
                        k['dev_type_id'] = k.pop('id_dev_type_id')
                        k['drawing_type'] = k.pop('drawing_type_name')
                        kk.append(k)

                    i['valid'] = valid_c
                    i['enabled'] = en
                    i['create_time'] = i['create_time'].strftime("%Y-%m-%d %H:%M:%S")
                    i['modify_time'] = i['modify_time'].strftime("%Y-%m-%d %H:%M:%S")
                    # i['upload_time'] = i['upload_time'].strftime("%Y-%m-%d %H:%M:%S")
                    i.pop('upload_time')
                    i['copy_id'] = i.pop('id_copy')
                    i['stage_type_id'] = i.pop('id_stage_type')
                    i['dev_type_id'] = i.pop('id_dev_type')
                    i['drawing_type_id'] = i.pop('id_drawing_type')
                    i['cutter_type_id'] = i.pop('id_cutter_type')
                    i['file'] = kk
                    content['payload']['data'].append(i)
            content["payload"]["page"] = {'count': page_class_k.count, 'page': int(page_num),
                                          'page_number': page_class_k.page_range[-1]}

        except Exception as e:
            content['status'] = 0
            content['errmsg'] = str(e)
            content['payload'] = []
    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def Custter_Case(request, pk):
    content = {"payload": [], "status": 1, "errmsg": ""}
    content["payload"] = {"case_name": [], "custters_spec": []}
    if request.method == "GET":
        if int(pk) == 0:
            case_name = []
            custters_spec = []
            cn = models.TbCustomerPaper.objects.all().values('case_name')
            for i in cn:
                for ke, ve in i.items():
                    case_name.append(ve)
            case_name_no_repeat = list(set(case_name))
            cs = models.TbCustomerPaper.objects.all().values('custters_spec')
            for j in cs:
                for kj, vj in j.items():
                    custters_spec.append(vj)
            custters_spec_no_repeat = list(set(custters_spec))
            content['payload']['case_name'] = case_name_no_repeat
            content['payload']['custters_spec'] = custters_spec_no_repeat
            content['errmsg'] = ''
            content['status'] = 1
        elif int(pk) == 1:
            case_name = []
            custters_spec = []
            cn = models.TbProjectPaper.objects.all().values('case_name')
            for i in cn:
                for ke, ve in i.items():
                    case_name.append(ve)
            case_name_no_repeat = list(set(case_name))
            cs = models.TbProjectPaper.objects.all().values('custters_spec')
            for j in cs:
                for kj, vj in j.items():
                    custters_spec.append(vj)
            custters_spec_no_repeat = list(set(custters_spec))
            content['payload']['case_name'] = case_name_no_repeat
            content['payload']['custters_spec'] = custters_spec_no_repeat
            content['errmsg'] = ''
            content['status'] = 1
    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def Custter_type(request):
    content = {"payload": [], "status": 1, "errmsg": ""}
    if request.method == "GET":
        type = request.GET.get('type')
        if type == 'customer':
            custters_spec_customer = []
            cn = models.TbCustomerPaper.objects.all().values('custters_spec')
            for i in cn:
                for ke, ve in i.items():
                    if ve != None:
                        custters_spec_customer.append(ve)
            case_name_no_repeat = list(set(custters_spec_customer))
            content['payload'] = case_name_no_repeat
            content['errmsg'] = ''
            content['status'] = 1
        if type == 'project':
            custters_spec_project = []
            pn = models.TbProjectPaper.objects.all().values('custters_spec')
            for i in pn:
                for ke, ve in i.items():
                    if ve != None:
                        custters_spec_project.append(ve)
            case_name_no_repeat = list(set(custters_spec_project))
            content['payload'] = case_name_no_repeat
            content['errmsg'] = ''
            content['status'] = 1
    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def Case_name(request):
    content = {"payload": [], "status": 1, "errmsg": ""}
    if request.method == "GET":
        type = request.GET.get('type')
        if type == 'customer':
            custters_spec_customer = []
            cn = models.TbCustomerPaper.objects.all().values('case_name')
            for i in cn:
                for ke, ve in i.items():
                    if ve != None:
                        custters_spec_customer.append(ve)
            case_name_no_repeat = list(set(custters_spec_customer))
            content['payload'] = case_name_no_repeat
            content['errmsg'] = ''
            content['status'] = 1
        if type == 'project':
            custters_spec_project = []
            pn = models.TbProjectPaper.objects.all().values('case_name')
            for i in pn:
                for ke, ve in i.items():
                    if ve != None:
                        custters_spec_project.append(ve)
            case_name_no_repeat = list(set(custters_spec_project))
            content['payload'] = case_name_no_repeat
            content['errmsg'] = ''
            content['status'] = 1
    return content


# 机型接口
@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def DevType(request):
    content = {"payload": [], "status": 1, "errmsg": ""}
    if request.method == 'GET':
        dl = []
        try:
            search = request.GET.get("search", None)
            page_num = request.GET.get("page", None)
            if search:
                data = models.TbTypeDevice.objects.filter(Q(id__contains=search) |
                                                          Q(dev_type__contains=search))
            else:
                data = models.TbTypeDevice.objects.all()
            if page_num:
                page_class = Paginator(data, 20)
            else:
                page_class = Paginator(data, len(data) + 1)
                page_num = 1
            select_data = page_class.page(page_num)  # 第n页中的内容
            content["payload"] = {"data": [], "page": {}}  # 定义payload的输出格式
            if select_data:
                for i in select_data:
                    dl.append({'dev_type': i.dev_type,
                               'id': i.id,
                               'create_people': i.create_people,
                               'create_time': (i.create_time).strftime('%Y-%m-%d %H:%M:%S')
                               })
            content['payload'] = dl
            content['errmsg'] = ''
            content['status'] = 1
        except Exception as e:
            content['payload'] = []
            content['errmsg'] = str(e)
            content['status'] = 0
    if request.method == 'POST':
        try:
            dev_type = request.POST.get('dev_type')
            create_people = request.user.username + "(" + request.user.last_name + ")"  # 获取当前登陆用户名
            if create_people:
                create_people = str(create_people).split('(')[0]
            create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # 创建时间
            models.TbTypeDevice.objects.update(dev_type=dev_type, create_people=create_people, create_time=create_time)
            content['payload'] = 'add success!'
            content['errmsg'] = ''
            content['status'] = 1
        except Exception as e:
            content['payload'] = []
            content['errmsg'] = str(e)
            content['status'] = 0
    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def Dev_Typepk(request, pk):
    content = {"payload": [], "status": 1, "errmsg": ""}
    if request.method == 'GET':
        try:
            search = request.GET.get("search", None)
            page_num = request.GET.get("page", None)
            if search:
                data = models.TbTypeDevice.objects.filter(id=int(pk)).filter(Q(id__contains=search) |
                                                                             Q(dev_type__contains=search))
            else:
                data = models.TbTypeDevice.objects.filter(id=int(pk)).all()
            if page_num:
                page_class = Paginator(data, 20)
            else:
                page_class = Paginator(data, len(data) + 1)
                page_num = 1
            select_data = page_class.page(page_num)  # 第n页中的内容
            content["payload"] = {"data": [], "page": {}}  # 定义payload的输出格式
            if select_data:
                for i in select_data:
                    content['payload'] = {'dev_type': i.dev_type,
                                          'id': i.id,
                                          'create_people': i.create_people,
                                          'create_time': (i.create_time).strftime('%Y-%m-%d %H:%M:%S')
                                          }
            # content['payload'] = dl
            content['errmsg'] = ''
            content['status'] = 1
        except Exception as e:
            content['payload'] = []
            content['errmsg'] = str(e)
            content['status'] = 0

    if request.method == 'PUT':
        try:
            dev_type = request.POST.get('dev_type')
            create_people = request.user.username + "(" + request.user.last_name + ")"  # 获取当前登陆用户名
            if create_people:
                create_people = str(create_people).split('(')[0]
            dt = models.TbTypeDevice.objects.filter(id=int(pk))
            dt.update(dev_type=dev_type, create_people=create_people)

            content['payload'] = 'modify success.'
            content['errmsg'] = ''
            content['status'] = 1
        except Exception as e:
            content['payload'] = ''
            content['errmsg'] = str(e)
            content['status'] = 0

    if request.method == 'DELETE':
        try:
            models.TbTypeDevice.objects.filter(id=int(pk)).delete()
            content['payload'] = 'delete success.'
            content['errmsg'] = ''
            content['status'] = 1
        except Exception as e:
            content['payload'] = ''
            content['errmsg'] = str(e)
            content['status'] = 0
    return content


@api_view(http_method_names=["GET", "PUT", "POST", "DELETE"])
@wrapp
def cp_custters_spec(request, pk):
    """
    工程图纸接口
    :param request:
    :return:
    """
    content = {"payload": [], "status": 1, "errmsg": ""}
    try:
        if request.method == 'GET':
            if pk:
                custters_spec = models.TbCustomerPaper.objects.filter(id=int(pk)).values('custters_spec')[0][
                    'custters_spec']
                if custters_spec:
                    content['payload'] = str(custters_spec)
                    content['errmsg'] = ''
                    content['status'] = 1
                    return content
                else:
                    content['payload'] = []
                    content['errmsg'] = '沒有找到客戶圖紙裏面的刀具規格.'
                    content['status'] = 0
                    return content
            else:
                content['payload'] = []
                content['errmsg'] = '請輸入客戶圖紙的id.'
                content['status'] = 0
                return content
    except Exception as e:
        content['payload'] = []
        content['errmsg'] = str(e)
        content['status'] = 0
        return content